﻿using AChance.Func;
using System;
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;

namespace AChance.Dal.Func
{
    public static class DalKey
    {
        private static ConcurrentDictionary<string, DateTime> _keys = new ConcurrentDictionary<string, DateTime>();
        public static string Create<T>() where T : class
        {
            return Create<T>(FunContext.OrganNo);
        }
        public static string Create<T>(string organNo) where T : class
        {
            return Create(organNo, typeof(T).Name);
        }
        [MethodImpl(MethodImplOptions.Synchronized)]
        public static string Create(string organNo, string tableName)
        {
            if (organNo.Length != 10 || tableName.Length != 6)
                return null;
            string keyHead = organNo + tableName.Substring(3);
            DateTime now = DateTime.Now;
            DateTime keyTail = _keys.GetOrAdd(keyHead, now);
            keyTail = keyTail.ToString("yyyyMMddHHmmssfff").CompareTo(now.ToString("yyyyMMddHHmmssfff")) >= 0 ? keyTail.AddMilliseconds(1) : now;
            _keys[keyHead] = keyTail;
            return keyHead + keyTail.ToString("yyyyMMddHHmmssfff") + FunRedis.User.No;
        }
    }
}
